<script lang="ts" setup>
import { ref, toRefs, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { grantBusDataPermission, queryBus, queryBusDataPermission } from '/@/api/user'

const props = defineProps({
  visible: Boolean,
  user: Object
})
const { visible: vis, user } = toRefs(props)

const filterText = ref('')

interface Tree {
  id: string
  name: string
  dataList?: Tree[]
  type: string
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const data = ref<Tree[]>([])
const treeRef = ref()
const loading = ref(false)

const treeProps = {
  children: 'dataList',
  label: 'name',
}

const handleOpen = () => {
  loading.value = true
  queryBusDataPermission({ userId: user?.value?.id }).then(res => {
    let resData = res.data as any[]
    let keys = [] as any[]
    resData.forEach(item => {
      keys.push(`${item.categoryId},${item.dataId}`)
    })
    setCheckedKeys(keys)
  }).finally(() => {
    loading.value = false
  })
}

const setCheckedKeys = (keys: any[]) => {
  treeRef.value!.setCheckedKeys(keys, true)
}

const emit = defineEmits(['update:visible', 'success'])
const confirmClick = () => {
  grantBusDataPermission({
    dataList: treeRef.value!.getCheckedKeys(true).map((item:any) => ({
      categoryId: item.split(',')[0],
      dataId: item.split(',')[1]
    })),
    userId: user?.value?.id
  }).then(() => {
    ElMessage.success('授权成功！')
    emit('update:visible', false)
    emit('success')
  })
}

const getTreeData = () => {
  queryBus().then(res => {
    let resData = res.data
    // 因为保存接口需要获取父选项id，并且子选项id可能重复，这里把父id加在了子id前面以避免重复和后续操作方便
    resData.forEach(item => {
      if (item.dataList) {
        item.dataList.forEach(v => {
          v.id = item.id + ',' + v.id
        })
      }
    })
    data.value = resData
  })
}

const cancelHandler = () => {
  emit('update:visible', false)
}

getTreeData()
</script>

<template>
  <el-drawer v-model="vis" title="行级权限" @open="handleOpen" @close="cancelHandler">
    <el-input
      v-model="filterText"
      placeholder="输入关键词过滤"
      style="margin-bottom: 20px;"
    />
    <el-tree
      ref="treeRef"
      :props="treeProps"
      :data="data"
      show-checkbox
      node-key="id"
      v-loading="loading"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
    />
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelHandler">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="less" scoped>
</style>